/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mailctrl;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
/**
 *
 * @author flintx
 */
public class MailCtrl {

    String to = "";
    String from = "";
    String username = "";
    String password = "";
    String filename = "";
    String subject = "";
    String content = "";
    String mailserver = "";
    String servertype ="";
    Vector file = new Vector();

    public MailCtrl()
    {

    }

    public MailCtrl(String to, String from, String smtpServer, String username,
            String password, String subject, String content)
    {
        this.to = to;
        this.from = from;
        this.mailserver = smtpServer;
        this.username = username;
        this.password = password;
        this.subject = subject;
        this.content = content;
    }

    public void setMailServer(String mailserv)
    {
        this.mailserver = mailserv;
    }

    public void setPassWord(String pwd)
    {
        this.password = pwd;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public void setTo(String to)
    {
        this.to = to;
    }

    public void setFrom(String from)
    {
        this.from = from;
    }

    public void setSubject(String subject)
    {
        this.subject = subject;
    }

    public void setContent(String content)
    {
        this.content = content;
    }

    public void setServerType(String type)
    {
        this.servertype  = type;
    }
    public String transferChinese(String strText)
    {
        try{
            strText = MimeUtility.encodeText(new String(strText.getBytes(), "GB2312"), "GB2312", "B");
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return strText;
    }

    public void attachfile(String fname)
    {
        file.addElement(fname);
    }

    public static void setMailInfo(Message message)
    {
        
    }
    /*
方法说明：打印邮件信息
输入参数：Message message 信息对象
返回类型：
  */
 public static void printMessage(Message message){
  try{
   //获得发送邮件地址
   String from=((InternetAddress)message.getFrom()[0]).getPersonal();
   if (from==null) from=((InternetAddress)message.getFrom()[0]).getAddress();
  
   //获取主题
   String subject=message.getSubject();
   //System.out.println("SUBJECT: "+subject);
   if(subject.equals("mailctrl"))
   {
       System.out.print("FROM: "+from+" ");
       Part messagePart=message;
       Object content=messagePart.getContent();

       //附件
       if (content instanceof Multipart){
        messagePart=((Multipart)content).getBodyPart(0);
        System.out.println("[ Multipart Message ]");
       }
       Date recvdate = message.getSentDate();
       //获取content类型
       String contentType=messagePart.getContentType();
       //如果邮件内容是纯文本或者是HTML，那么打印出信息
       System.out.println("CONTENT:"+contentType);
       if (contentType.startsWith("text/plain")||
         contentType.startsWith("text/html")){
        InputStream is = messagePart.getInputStream();
        MailParser parser = new MailParser();
        parser.setSendDate(recvdate);
        parser.parserXml(is);
   }
   System.out.println("-------------- END ---------------");
   }
   //获取信息对象   
  }catch (Exception ex){
   ex.printStackTrace();
  }
 }

    public boolean sendMail()
    {
        Properties props = System.getProperties();
        props.put("mail.smtp.host", mailserver);
        props.put("mail.smtp.auth", "true");
        props.put("username", username);
        props.put("password", password);

        //if(this.smtp.indexOf("smtp.gmail.com")>=0)
        if(mailserver.indexOf("smtp.gmail.com")>=0)
        {

                 props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                 props.setProperty("mail.smtp.socketFactory.fallback", "false");
                 props.setProperty("mail.smtp.port", "465");
                 props.setProperty("mail.smtp.socketFactory.port", "465");
        }

        Authenticator auth = new PopupAuthenticator(username, password);
        Session session = Session.getDefaultInstance(props, auth);

        try{
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            InternetAddress[] address = { new InternetAddress(to)};
            msg.setRecipients(Message.RecipientType.TO,address);
            subject = transferChinese(subject);
            msg.setSubject(subject);

            Multipart mp = new MimeMultipart();
            MimeBodyPart mbpContent = new MimeBodyPart();
            mbpContent.setText(content);
            mp.addBodyPart(mbpContent);
            
            Enumeration efile = file.elements();
            while(efile.hasMoreElements())
            {
                MimeBodyPart mbpFile = new MimeBodyPart();
                filename = efile.nextElement().toString();
                FileDataSource fds = new FileDataSource(filename);
                mbpFile.setDataHandler(new DataHandler(fds));
                mbpFile.setFileName(fds.getName());
                mp.addBodyPart(mbpFile);
            }
            file.removeAllElements();
            msg.setContent(mp);
            msg.setSentDate(new Date());
            Transport.send(msg);
        }catch(MessagingException mex)
        {
            mex.printStackTrace();
            Exception ex = null;
            if((ex = mex.getNextException()) != null)
            {
                ex.printStackTrace();
            }
            return false;
        }
        return true;
    }

    public boolean recvMailFromPop3()
    {
        Store store = null;
        Folder folder = null;
        try{
            Properties props = System.getProperties();
            props.put("mail.pop3.host ", mailserver);
            Session session = Session.getDefaultInstance(props, null);
            store = session.getStore("pop3");
            store.connect(mailserver, username, password);

            folder = store.getDefaultFolder();
            if (folder == null) throw new Exception("No default folder");
            folder = folder.getFolder("INBOX");
            if (folder == null) throw new Exception("No POP3 INBOX");
            folder.open(Folder.READ_ONLY);
            Message[] msgs = folder.getMessages();
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for(int msgNum = msgs.length - 1; msgNum >= 0; msgNum--)
            {
                printMessage(msgs[msgNum]);
            }
            }catch(Exception ex)
            {
                ex.printStackTrace();
            }

            finally
            {
                 try{
                        if(folder != null)
                        folder.close(false);
                        if(store != null)
                        store.close();
                     }catch(Exception ex){
                            ex.printStackTrace();
                     }
            }
            return false;
    }

    public boolean recvMailFromIMAP()
    {
        IMAPFolder folder= null;
        IMAPStore store=null;
        try{
            Properties props = System.getProperties();
            props.put("mail.imap.host",mailserver);
            props.put("mail.imap.auth.plain.disable","true");
            Session session = Session.getDefaultInstance(props, null);
            store=(IMAPStore)session.getStore("imap");
            store.connect(mailserver, username, password);
            folder=(IMAPFolder)store.getFolder("INBOX");
           
            if (folder == null) throw new Exception("No POP3 INBOX");
            folder.open(Folder.READ_WRITE);
            Message[] msgs = folder.getMessages();
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for(int msgNum = msgs.length; msgNum >= 0; msgNum--)
            {
                printMessage(msgs[msgNum]);
            }
            }catch(Exception ex){
                ex.printStackTrace();
        }
        finally
        {
            try{
                if(folder != null)
                    folder.close(false);
                if(store != null)
                    store.close();
            }catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
        return false;
    }
    public boolean recvMail()
    {
        if(servertype.equals("pop3"))
        {
            return recvMailFromPop3();
        }
        else if(servertype.equals("imap"))
        {
            return recvMailFromIMAP();
        }
        else
        {
            System.out.println("mail server type was not set");
            return false;
        }
    }

    public static void main(String[] args) throws IOException
    {
        MailCtrl mailctrl = new MailCtrl();
        mailctrl.setServerType("pop3");
        mailctrl.setUsername("eagleskys");
        mailctrl.setPassWord("19850724");
        /*mailctrl.setMailServer("smtp.gmail.com");
        mailctrl.setTo("eagleskys@126.com");
        mailctrl.setFrom("eagleskys@gmail.com");
        mailctrl.setSubject("mailctrl");
        MailCreater mailcrt = new MailCreater();
        mailcrt.newXMLMail();
        mailcrt.addOperation( mailcrt.packageOperation("qq", "d:/program/qq", null));
        mailctrl.setContent(mailcrt.buildMailContent());
        mailctrl.sendMail();*/
        mailctrl.setMailServer("pop3.126.com");
        mailctrl.recvMail();
    }

}

class PopupAuthenticator extends Authenticator {
    private String user;
    private String pwd;
    public PopupAuthenticator(String user, String pwd) {
        this.user = user;
        this.pwd = pwd;
    }
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, pwd);
    }
}

